/*
       This MP3 Player script has been custom written by Adam Khoury at www.developphp.com
	   He used the Flash Help file to get all the code needed for the sound programming mechanisms
       For help on any parts of the code you do not understand post up in our forum
	   
	   OK let's break it down.... check code in frame 1, 2, and 3,  most is on frame 3
	   There is drag code inside the volume & pan silders, but everything else is in plain view on frame 3

*/

// Assign var that has to do with how many tracks we want to play from our folder
var tracksInFolder:Number = 8;
// Assign var for default start track number, usually start playing track 1
var trackPlayNum:Number = 1;
// Initialize the pause position
var pausePosition:int = 0;
//=====================================================================================================
// Here we set the URL request for track 1
// It usually gets swapped out when we say "gotoAndPlay(2)" in the code on frame 3
// but not every time, we also use it for the scrubber, scrubbing sends to frame 2 also
// The code in frame 3 tells this "trackPlayNum" var below what to be upon swap
// That is how the playlist functionality occurs, and song swap out
var req:URLRequest = new URLRequest("mp3_files/song" + trackPlayNum + ".mp3");
//=====================================================================================================
stop();
// Create the sound object
var snd:Sound = new Sound();
// Assign a var name for the sound channel
var channel:SoundChannel;
// Boolean value for button functions, to switch in the conditionals
var isPlaying:Boolean = false;
// Set the play buffer to 5 seconds, you can adjust this
var context:SoundLoaderContext = new SoundLoaderContext(5000, true);
// Load the requested URL sound into the snd var, along with context
snd.load(req, context);
// Create the play channel using snd
channel = snd.play(pausePosition); // Start playing
// Set "isPalying" to true initially
isPlaying = true; 
// make play button show pause symbol
playBtn.gotoAndStop(2);
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// New track play function
function newTrack():void {
	 if (trackPlayNum < tracksInFolder) {
         channel.stop();  
         trackPlayNum += 1;
	     gotoAndPlay(2);
	    } else {
         channel.stop();  
         trackPlayNum = 1;
	     gotoAndPlay(2);
	    }
		// Always set pausePosition back to 0 here
		pausePosition = 0;
} /// Close newTrack function
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Listen for the onPlaybackComplete function directly below
channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);
// This onPlaybackComplete fires off when tracks finish playing
function onPlaybackComplete(event:Event) {
	// Run the newTrack() function above every time a song completes
	newTrack();
}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
///  Get ID3 info for each track playing ////////////////////
snd.addEventListener(Event.ID3, onID3InfoReceived); 
function onID3InfoReceived (event:Event):void {
	
	var songName:String;
	var artist:String;
	if (snd.id3.songName != null){
		songName = snd.id3.songName;
	} else {
		songName = "Title Unknown";
	}
	if (snd.id3.artist != null){
		artist = snd.id3.artist;
	} else {
		artist = "Unknown Artist";
	}
	// Now here we add the info to the songInfo text on stage
	songInfoClip.scrollingText.songInfo_txt.text = songName + "  -  "  + artist;
}
////// END ID3 Info Gathering
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Play & Pause Function //////////////////////////////////////////////////////
function playPause(event:MouseEvent):void {
   
   if (isPlaying == true) {
	   
	   pausePosition = channel.position;
       channel.stop();
	   playBtn.gotoAndStop(1);
       isPlaying = false;

    } else {
			 
       channel = snd.play(pausePosition);
	   playBtn.gotoAndStop(2);
	   isPlaying = true;
	}

}
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
// Play Next Song Function ////////////////////////////////////
function nextSound(event:MouseEvent):void {
     
	 if (trackPlayNum < tracksInFolder) {
		          if (snd.bytesLoaded != snd.bytesTotal) {
			         channel.stop();
					 snd.close();
                     trackPlayNum += 1;
	                 gotoAndPlay(2);
		          } else {
			         channel.stop();  
                     trackPlayNum += 1;
	                 gotoAndPlay(2);
		          }
	    } else {
		          if (snd.bytesLoaded != snd.bytesTotal) {
			         channel.stop();
					 snd.close();
                     trackPlayNum = 1;
	                gotoAndPlay(2);
		          } else {
			        channel.stop();
                    trackPlayNum = 1;
	                gotoAndPlay(2);	
		          }
	    }
	 pausePosition = 0;
}
////////////////////////////////////////////////////////////////////////////////////

// Play Previous Song Function //////////////////////////////
function previousSound(event:MouseEvent):void {
       
	 if (trackPlayNum == 1) {
		        
				if (snd.bytesLoaded != snd.bytesTotal) {
			         channel.stop();
					 snd.close();
                     trackPlayNum += 1;
	                 gotoAndPlay(2);
		          } else {
	                channel.stop();
                    trackPlayNum = tracksInFolder;
	                gotoAndPlay(2);
		          }		 

			
	 } else {
		 
		          if (snd.bytesLoaded != snd.bytesTotal) {
			        channel.stop();
					snd.close();
                    trackPlayNum -= 1;
	                gotoAndPlay(2);	
		          } else {
			        channel.stop();
                    trackPlayNum -= 1;
	                gotoAndPlay(2);	
		          }		 
	 
	 }
	 pausePosition = 0;
}
////////////////////////////////////////////////////////////////////////////////////

// Button Listeners ///////////////////////////////////////////////////////////////////////
playBtn.addEventListener(MouseEvent.CLICK, playPause);
previousBtn.addEventListener(MouseEvent.CLICK, previousSound);
nextBtn.addEventListener(MouseEvent.CLICK, nextSound);
//autoPlayIcon.addEventListener(MouseEvent.CLICK, toggleAutoPlay);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////// AutoPlay Function ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*function toggleAutoPlay ():void {

}*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	///////////////   Track Scrubber and Ghost Scrub Knob /////////////////////////////////////////////////////////////////////////////////
// ------------------------------------------------------------------ Along with the follower clip inside the trackScrubber
var isDragging:Boolean;
trackScrubber.ghostKnob.visible = false;
// Set Bounds
var scrubberBounds = new Rectangle(0,trackScrubber.ghostKnob.y,trackScrubber.scrubberRect.width,0);
trackScrubber.addEventListener(MouseEvent.MOUSE_DOWN, dragScrub);
stage.addEventListener(MouseEvent.MOUSE_UP, dropScrub);

         // Drag scrubber
		function dragScrub(evt:Event):void {

			trackScrubber.ghostKnob.startDrag(true,scrubberBounds);
			trackScrubber.ghostKnob.visible = true;
            isDragging = true;
		}
         // Drop scrubber
		function dropScrub (evt:Event):void {
			
             if (isPlaying == true) {
				if (isDragging == true) {
                     stopDrag();
					 // Calculate full time of this track
					 var fullTime:int = Math.floor(snd.length / 1000);
					 // Claim a var for the position the song is where we release the scrubber after dragging
	                 var newPos:Number = fullTime / 100 * Math.floor(trackScrubber.ghostKnob.x * 1000);
					 // Important to set new pause position here
	                 pausePosition = newPos / 2;
					 channel.stop();
					 gotoAndPlay(2);
	                 //channel = snd.play(newPos);
					 isPlaying = true; 
					 isDragging = false;

				  }
				} else { // if not playing
					isDragging = false;
					 trackScrubber.ghostKnob.visible = false;
					//pausePosition = fullTime / 100 * Math.floor(trackScrubber.tBarKnob.x * 1000);

				}
		
		}
///////////////   End Track Scrubber and Seek Bar //////////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Add listener to trigger [onEnterFrame] function below
addEventListener(Event.ENTER_FRAME, onEnterFrame);

function onEnterFrame(event:Event):void {
	
	// Set and change volume if they drag
    var volumeLevel = channel.soundTransform;
	var newLevel:Number = (volumeSlider.knob.x) / -100;
	volumeLevel.volume = newLevel;
	channel.soundTransform = volumeLevel;
	volumeSlider.volumeLightBar.width = volumeSlider.knob.x;
	// Set and change pan if they drag
	var panLevel = channel.soundTransform;
	var newPan:Number = (panSlider.knob.x / 100) - 1;
	panLevel.pan = newPan;
	channel.soundTransform = panLevel;
	
    // SPEAKER 1 BOUNCE (left channel)
    spkr1.width = ( Math.round(channel.leftPeak * 8) ) + 60; // 60 is speaker width
    spkr1.height = ( Math.round(channel.leftPeak * 8) ) + 60; // 60 is speaker height

    // SPEAKER 2 BOUNCE (right channel)
    spkr2.width = ( Math.round(channel.rightPeak * 8) ) + 60; // 60 is speaker width
    spkr2.height = ( Math.round(channel.rightPeak * 8) ) + 60; // 60 is speaker height
	// ANIMATED EQ BARS MASK CODE
    maskEQ1.width = (Math.round(channel.leftPeak * 27) ); // 27 is the width of the EQ masks
    maskEQ2.width = (Math.round(channel.rightPeak * 27) ); // 27 is the width of the EQ masks
	bars1.mask = maskEQ1;
	bars2.mask = maskEQ2;
	// Get full time
	var tallytime = (snd.length/1000);
	var totalmins:Number = Math.floor(tallytime /60);
	var totalsecs = Math.floor (tallytime) % 60;
	if (totalsecs < 10){
		totalsecs = "0" + totalsecs;
	}
	displayFullTime.text = ( " " + totalmins+ ":" + totalsecs);

	// End get Full time
	// Get playing time
	var totalSeconds:Number = channel.position/1000;
	var minutes:Number = Math.floor(totalSeconds /60);
	var seconds = Math.floor (totalSeconds) % 60;
	if (seconds < 10){
		seconds = "0" + seconds;
	}
	displayTime.text = ( " " + minutes+ ":" + seconds);
	// End get playing time

	/// progress bar code...
	var estimatedLength:int = Math.ceil(snd.length / (snd.bytesLoaded / snd.bytesTotal));
	var playbackPercent:uint = 100 * (channel.position / estimatedLength );
	// I want my position bar to be 200 pixels wide on completion so I multiply the percentage x 2
	trackScrubber.positionBar.width = playbackPercent * 2;
	trackScrubber.follower.x = trackScrubber.positionBar.width;
	// make the loaded progress bar that lives under the playhead progress bar grow dynamically
	var loadedPercent:uint = 100 * (snd.bytesLoaded / snd.bytesTotal);
	trackScrubber.loadedProgressBar.width = loadedPercent * 2;
}



// Place track amount and current track # into a text field
songCount_txt.text = "Track " + trackPlayNum + " of " + tracksInFolder;
//=====================================================================================================
// Make the lit volume meter synch up to the knob position
volumeLightBar.width = knob.x;

// Hint: Place the volume knob at an offset position according to its width
// Since my knob is 10px wide, and my bar is 100px wide, I placed my knob
// at an x position of 90 to start

// Volume Code for Draggable Volume Slider /////////////////////////////////////////////////////////////
var knobWidth:Number = knob.width;
var rectWidth:Number = rect.width;
var rectX:Number = rect.x;
// Do math to correctly make the drag bounds using values attained above
var boundWidth = rectWidth - knobWidth;
// Now apply the variable numbers with the math we want as bounds
var boundsRect:Rectangle = new Rectangle(rectX, 0, boundWidth, 0);
// Enable drag
knob.addEventListener(MouseEvent.MOUSE_DOWN, Drag);
function Drag(event:MouseEvent) {
	// Here you see we apply the boundsRect when they drag
	knob.startDrag(false, boundsRect);
}

// Stop drag
stage.addEventListener(MouseEvent.MOUSE_UP, Drop);
function Drop(event:MouseEvent) {
	knob.stopDrag();
}
//=====================================================================================================
function startPan(event:MouseEvent):void{
	
	knob.startDrag(true, panBounds);
	
}
//////////////////
function stopPan(event:MouseEvent):void{
	
	knob.stopDrag();
	
}
//////////////////////
var panBounds:Rectangle = new Rectangle (0, 0, 200, 0);
/////////////////////
knob.addEventListener(MouseEvent.MOUSE_DOWN, startPan);
knob.addEventListener(MouseEvent.MOUSE_UP, stopPan);